package com.maddox.maddoxppjoke.util;

import android.content.ComponentName;

import androidx.fragment.app.FragmentActivity;
import androidx.navigation.ActivityNavigator;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.FragmentNavigator;

import com.maddox.libcommon.utils.AppGlobals;
import com.maddox.maddoxppjoke.model.Destination;
import com.maddox.maddoxppjoke.navigator.FixFragmentNavigator;

import java.util.HashMap;

/**
 * 导航信息构建
 */
public class NavGraphBuilder {

    public static void build(NavController navController, FragmentActivity activity, int containerId) {

        NavigatorProvider navigatorProvider = navController.getNavigatorProvider();

        //获取Activity导航管理器
        ActivityNavigator activityNavigator = navigatorProvider.getNavigator(ActivityNavigator.class);

        //获取Fragment导航管理器
//        FragmentNavigator fragmentNavigator = navigatorProvider.getNavigator(FragmentNavigator.class);

        //使用自定义的Fragment导航器,解决每次都要重新创建Fragment的问题
        FixFragmentNavigator fragmentNavigator = new FixFragmentNavigator(activity, activity.getSupportFragmentManager(), containerId);
        navigatorProvider.addNavigator(fragmentNavigator);

        //创建导航信息路由器
        NavGraph graph = new NavGraph(new NavGraphNavigator(navigatorProvider));

        //遍历自己封装的导航信息集合,设置到路由器中
        HashMap<String, Destination> destConfig = AppConfig.getDestConfig();
        for (Destination destination : destConfig.values()) {
            //Fragment类型
            if (destination.isFragment()) {
                FragmentNavigator.Destination fragmentDestination = fragmentNavigator.createDestination();
                fragmentDestination.setClassName(destination.getClassName());
                fragmentDestination.setId(destination.getId());
                fragmentDestination.addDeepLink(destination.getPageUrl());
                graph.addDestination(fragmentDestination);
            } else {
                //Activity类型
                ActivityNavigator.Destination activityDestination = activityNavigator.createDestination();
                activityDestination.setId(destination.getId());
                activityDestination.addDeepLink(destination.getPageUrl());
                activityDestination.setComponentName(new ComponentName(AppGlobals.getApplication().getPackageName(), destination.getClassName()));
                graph.addDestination(activityDestination);

            }
            //设置首页默认
            if (destination.isAsStarter()) {
                graph.setStartDestination(destination.getId());
            }

        }
        //将路由器设置给页面导航控制器
        navController.setGraph(graph);

    }


}
